<template>
  <div class="dashboard">
    <!-- 主内容区域 -->
    <div class="content">
      <div v-if="activeTab === 0">
        <!-- 首页内容 -->
        <div class="cards">
          <div class="card" v-for="(item, index) in cardData" :key="index">
            <div class="card-header">
              <i class="icon">📘</i>
              <span>{{ item.title }}</span>
            </div>
            <!-- 今日营业信息 -->
            <div class="card-content">
              <p>总订单数：<span>{{ item.totalOrders }}</span></p>
              <p>总金额数：<span>{{ item.totalAmount }}</span></p>
              <p>涉及信息:</p>
              <!-- 这里放数组的数据 -->
              <ul v-if="item.detail && item.detail.length" class="detail-list">
                <li v-for="(detailItem, index) in item.detail" :key="index">
                  {{ detailItem.Name }} - {{ detailItem.orderNum }}个订单 - {{ detailItem.money }}元
                </li>
              </ul>
            </div>
          </div>

          <div>
            <p>今年总营业额：<span>{{ totalMoney }}</span></p>
            <p>今年总营收额：<span>{{ totalProfit }}</span></p>
          </div>
        </div>
        <div class="chart-container">
          <div class="chart-container-tab">
            <div>
              <h1>订单数量折线图</h1>
            </div>
            <el-form :model="queryParams" size="small" label-width="100px" class="search-form">
              <el-form-item label="订单开始日期" prop="orderStartDateRange">
                <el-date-picker clearable v-model="queryParams.orderStartDateRange" type="daterange"
                  value-format="yyyy-MM-dd" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 60%;"
                  @change="handleDateStartRangeChange" placeholder="请选择订单开始日期范围" />
              </el-form-item>
            </el-form>
          </div>
          <div id="chart-home" class="chart"></div>
          <div class="revenue-page">
            <h2>营收数据统计</h2>
            <div id="chart-revenue" class="chart"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getTodayRevenue,
  getMonthRevenue,
  getMonthCompanyOrderStatic,
  getMonthDriverMoneyStatic,
  getTimeRangeOrderStatic,
  getYearStatic
} from "@/api/fincal/analysis";
import * as echarts from 'echarts';

export default {
  data() {
    return {
      tabs: [
        { label: "营业统计" },
        { label: "营收统计" },
      ],
      activeTab: 0, // 当前激活的标签页索引
      //总营业额
      totalMoney: "",
      //总营收额
      totalProfit: "",
      cardData: [
        {
          title: "今日营业信息",
          totalOrders: "",
          totalAmount: "",
          detail: []
        },
        {
          title: "本月营业信息",
          totalOrders: "",
          totalAmount: "",
          detail: []
        },
        {
          title: "本月各企业订单信息",
          totalOrders: "",
          totalAmount: "",
          detail: []
        },
        {
          title: "本月司机排行榜",
          totalOrders: "",
          totalAmount: "",
          detail: []
        }
      ],
      // 查询参数
      queryParams: {
        // 订单开始日期范围
        orderStartDateRange: [],
        orderStartStartTime: this.$moment(new Date(new Date().setMonth(new Date().getMonth() - 1)).getTime()).format('YYYY-MM-DD'),
        orderStartEndTime: this.$moment(new Date().getTime()).format('YYYY-MM-DD'),
      },
      // 引入echarts的数据
      TimeRangeOrderNum: [],
      // ECharts 实例
      chartHome: null,
      chartRevenue: null,
    };
  },
  mounted() {
    this.fetchBussinessData();
    this.initCharts(); // 初始化图表
  },
  beforeDestroy() {
    // 销毁图表实例以防止内存泄漏
    if (this.chartHome) this.chartHome.dispose();
    if (this.chartRevenue) this.chartRevenue.dispose();
  },
  methods: {
    switchTab(index) {
      this.activeTab = index;
      // 切换标签时，刷新相应的图表
      this.refreshCharts();
    },
    handleDateStartRangeChange(dates) {
      if (dates && dates.length === 2) {
        this.queryParams.orderStartStartTime = dates[0]; // 设置开始日期
        this.queryParams.orderStartEndTime = dates[1];   // 设置结束日期
        this.fetchBussinessData(); // 重新获取数据并更新图表
      } else {
        this.queryParams.orderStartStartTime = "";
        this.queryParams.orderStartEndTime = "";
      }
    },

    // 请求营业数据
    async fetchBussinessData() {
      try {
        // 并行请求所有数据，提高效率
        const [
          todayRevenueResponse,
          monthRevenueResponse,
          companyOrderResponse,
          driverRankingResponse,
          TimeRangeOrderStatic,
          YearStatic
        ] = await Promise.all([
          getTodayRevenue({}),
          getMonthRevenue({}),
          getMonthCompanyOrderStatic({}),
          getMonthDriverMoneyStatic({}),
          getTimeRangeOrderStatic(this.queryParams),
          getYearStatic()
        ]);
        // 处理今日营业额
        if (todayRevenueResponse) {
          const data1 = todayRevenueResponse;
          this.cardData[0].totalOrders = `${data1.orderTotal}份`;
          this.cardData[0].totalAmount = `${data1.moneyTotal}元`;
          this.cardData[0].detail = data1.driverCarDetail.map(item => ({ Name: item.driverName, orderNum: item.orderNum, money: item.money }));
        }
        // 处理本月营业额
        if (monthRevenueResponse) {
          const data2 = monthRevenueResponse;
          this.cardData[1].totalOrders = `${data2.orderTotal}份`;
          this.cardData[1].totalAmount = `${data2.moneyTotal}元`;
          this.cardData[1].detail = data2.driverCarDetail.map(item => ({ Name: item.driverName, orderNum: item.orderNum, money: item.money }));
        }
        // 处理本月各企业订单数
        if (companyOrderResponse) {
          const data3 = companyOrderResponse;
          this.cardData[2].totalOrders = `${data3.orderTotal}份`;
          this.cardData[2].totalAmount = `${data3.moneyTotal}元`;
          this.cardData[2].detail = data3.companyOrderDetail.map(item => ({ Name: item.companyName, orderNum: item.orderNum, money: item.companyTotalMoney }));
        }
        // 处理本月驾驶员排行榜
        if (driverRankingResponse) {
          const data4 = driverRankingResponse;
          this.cardData[3].totalOrders = `${data4.orderTotal}份`;
          this.cardData[3].totalAmount = `${data4.moneyTotal}元`;
          this.cardData[3].detail = data4.driverCarDetail.map(item => ({ Name: item.driverName, orderNum: item.orderNum, money: item.money }));
        }
        // 订单折现图
        if (TimeRangeOrderStatic) {
          this.TimeRangeOrderNum = TimeRangeOrderStatic.data;
          this.updateChartHome(); // 更新图表
        }
        // 营业额，营收信息
        if (YearStatic) {
          this.totalMoney = YearStatic.data.totalMoney;
          this.totalProfit = YearStatic.data.totalProfit;
        } 
        // 您可以在此处添加更新其他图表的数据和调用相应的更新方法
        this.updateChartRevenue(); // 示例

      } catch (error) {
        console.error("Error fetching data:", error);
        // 在这里可以添加用户友好的错误提示，例如使用消息通知组件
        this.$notify({
          title: '错误',
          message: '数据加载失败，请稍后重试。',
          type: 'error'
        });
      }
    },

    // 初始化所有图表
    initCharts() {
      // 初始化首页图表
      const chartHomeDom = document.getElementById('chart-home');
      if (chartHomeDom) {
        this.chartHome = echarts.init(chartHomeDom);
        this.updateChartHome();
      }

      // 初始化营收统计图表
      const chartRevenueDom = document.getElementById('chart-revenue');
      if (chartRevenueDom) {
        this.chartRevenue = echarts.init(chartRevenueDom);
        this.updateChartRevenue();
      }
    },

    // 刷新所有图表
    refreshCharts() {
      this.updateChartHome();
      this.updateChartRevenue();
    },

    // 更新首页图表（订单数量折线图）
    updateChartHome() {
      if (!this.chartHome) return;
      const option = {
        title: {
          text: '订单数量折线图'
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: this.TimeRangeOrderNum.map(item => item.orderDate) // 假设数据中有日期字段
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          name: '订单数量',
          type: 'line',
          data: this.TimeRangeOrderNum.map(item => item.orderNum)
        }]
      };
      this.chartHome.setOption(option);
    },

    // 更新营收统计图表
    updateChartRevenue() {
      if (!this.chartRevenue) return;
      const option = {
        title: {
          text: '营收数据统计'
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: this.TimeRangeOrderNum.map(item => item.orderDate)
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          name: '营收金额',
          type: 'bar',
          data: this.TimeRangeOrderNum.map(item => item.orderProfitMoney)
        }]
      };
      this.chartRevenue.setOption(option);
    },
  },

  // 处理窗口大小变化
  resizeCharts() {
    if (this.chartHome) this.chartHome.resize();
    if (this.chartRevenue) this.chartRevenue.resize();

  },
};
</script>

<style scoped>
.dashboard {
  padding: 20px;
  font-family: Arial, sans-serif;
  background-color: #f7f8fa;
}

.notification-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  background: #eaf4fe;
  border-radius: 4px;
  margin-bottom: 20px;
}

.notification-bar .link {
  color: #007bff;
  text-decoration: none;
}

.tabs {
  display: flex;
  margin-bottom: 20px;
  background: #fff;
  padding: 10px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.tab {
  padding: 10px 20px;
  cursor: pointer;
  border-radius: 4px;
  margin-right: 10px;
  background: #f0f0f0;
}

.tab.active {
  background: #007bff;
  color: #fff;
}

.cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.card {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.chart-container,
.revenue-page {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.chart {
  width: 100%;
  height: 400px;
}

.search-form {
  background-color: #ffffff;
  padding: 18px;
  border-radius: 4px;
}

.chart-container-tab {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}
</style>
